import time
import schedule
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains
from chaojiying_Python import chaojiying


class BilibiliSpider:

    def __init__(self):
        # 初始化BilibiliSpider对象
        self.url = 'https://passport.bilibili.com/login'
        self.driver = webdriver.Chrome(ChromeDriverManager().install())
        self.driver.maximize_window()
        print(f"Driver type: {type(self.driver)}")
        self.username = 'LY酱'
        self.password = 'XLPjz963852'
        self.chaojiying_user_name = 'mrnerox'
        self.chaojiying_password = '123qwe,.'
        self.chaojiying_ID = '863c715c4ed6582b7ae3bf109d2a90f4'
        self.pic_id = ''
        self.chaojiying = chaojiying.Chaojiying_Client(
            self.chaojiying_user_name, self.chaojiying_password, self.chaojiying_ID
        )

    def open(self):
        # 打开Bilibili登录页面，并输入用户名和密码
        self.driver.get(self.url)
        # 使用 placeholder 属性定位输入框，添加等待时间
        username_input = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'input[placeholder="请输入账号"]'))
        )
        password_input = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'input[placeholder="请输入密码"]'))
        )
        # 输入用户名和密码
        username_input.send_keys(self.username)
        password_input.send_keys(self.password)
        print("输入账户密码完成")

    def get_touclick_button(self):
        # 定位登录按钮并点击
        button = self.driver.find_element(By.CLASS_NAME, "btn_primary")
        print("登录按钮已定位")
        time.sleep(2)
        button.click()
        time.sleep(2)
        print("登录按钮已点击")
        return button

    def pick_code(self):
        # 识别验证码并完成登录
        time.sleep(2)
        img_label = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, '.geetest_holder.geetest_silver'))
        )
        img_label.screenshot('yzm.png')
        print("图片已获取")

        cjy = chaojiying.Chaojiying_Client(self.chaojiying_user_name, self.chaojiying_password, self.chaojiying_ID)
        im = open('yzm.png', 'rb').read()
        result = cjy.PostPic(im, 9004)['pic_str']
        print(result)

        for index in result.split('|'):
            x = index.split(',')[0]
            y = index.split(',')[1]
            print(index)
            ActionChains(self.driver).move_to_element_with_offset(img_label, int(x), int(y)).click().perform()
            print('执行成功')
            time.sleep(2)

        time.sleep(1)
        btn = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_commit_tip'))
        )
        btn.click()
        print("点击完成，成功登录bilibili")

    def perform_click_action(self):
        # 点击热门标签和直播链接
        link_class_hot = "channel-icons__item"
        hot_title = "热门"
        link_class_live = "default-entry"
        live_text = "直播"
        click_count = 1

        time.sleep(1)

        for _ in range(click_count):
            self.click_link(link_class_hot, hot_title)
            time.sleep(1)
            self.click_link(link_class_live, live_text)
            time.sleep(1)

        self.driver.quit()

    def click_link(self, link_class, link_text):
        # 点击指定链接
        link_elements = WebDriverWait(self.driver, 10).until(
            EC.presence_of_all_elements_located((By.CLASS_NAME, link_class))
        )

        for link_element in link_elements:
            if link_text in link_element.text:
                try:
                    link_element.click()
                    time.sleep(1)
                except StaleElementReferenceException:
                    pass

    def main(self):
        """
        主函数
        :return:None
        """
        self.open()
        time.sleep(2)
        self.get_touclick_button()
        time.sleep(2)
        self.pick_code()
        time.sleep(2)
        self.perform_click_action()
        print("执行结束")


if __name__ == '__main__':
    bilibili = BilibiliSpider()
    print("阶段性完成")
    bilibili.main()
